<template>
  <div>
    <a-drawer
      :visible="visible"
      :title="title"
      :bodyStyle="{
        padding: '0px 20px',
      }"
      @close="cancelClick"
      :width="800"
      :destroyOnClose="true"
    >
      <a-card :bordered="false">
        <!-- <div class="textarea-wrapper">
          <div class="mask-text" v-if="isIndicator">
            <a-spin :indicator="indicator" />
            <div class="mask-box">音频合成中，请稍后...</div>
          </div>
        </div> -->
        <div class="dubbing">
          <div>
            <a-tabs v-model:activeKey="activeKey" @change="activeChange">
              <a-tab-pane
                v-for="tab in tabList"
                :key="tab.key"
                :tab="tab.value"
              />
            </a-tabs>
            <a-spin tip="加载中..." :spinning="loading">
              <div class="voice-content hide-scroller-bar">
                <div
                  class="n-tab-pane"
                  v-for="voice in voiceList"
                  :key="voice.gender_type"
                >
                  <div class="group-name">{{ voice.gender_title }}：</div>
                  <a-row style="flex: 1" :wrap="true">
                    <a-col
                      v-for="item in voice.item"
                      :key="item.id"
                      @click="voiceClick(item)"
                    >
                      <div
                        class="group-box"
                        :class="
                          timbreId == item.timbre_id ? 'group-border' : ''
                        "
                      >
                        <div class="right-badge" v-if="item.quality == 2">
                          <a-space :size="4">
                            <CrownOutlined style="font-size: 14px" />
                            精品
                          </a-space>
                          <!-- <cu-icon
                            type="icon-zuanshihuiyuan"
                            style="font-size: 18px"
                          /> -->
                        </div>
                        <div class="avatar">
                          <a-avatar :src="item.img" />
                          <div class="mask" @click="playbackClick(item)">
                            <PlayCircleOutlined
                              class="icon"
                              v-if="!item.isPlay"
                            />
                            <PauseCircleOutlined
                              class="icon"
                              v-if="item.isPlay"
                            />
                            <!-- <cu-icon
                              class="icon"
                              :type="
                                !item.isPlay ? 'icon-bofang1' : 'icon-zanting'
                              "
                            /> -->
                          </div>
                        </div>
                        <div>
                          <div>{{ item.name }}</div>
                          <div>{{ item.human_style }}</div>
                        </div>
                      </div>
                    </a-col>
                  </a-row>
                </div>
              </div>
            </a-spin>
          </div>
        </div>
        <div class="voice">
          <a-row align="middle" :gutter="[0, 16]">
            <a-col :span="24">
              <div class="voice-item">
                <div class="copywriting-title">语气：</div>
                <a-select
                  v-model:value="emotion_category"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="toneDisabled"
                >
                  <a-select-option
                    v-for="item in toneList"
                    :value="item.key"
                    :key="item.key"
                  >
                    {{ item.value }}
                  </a-select-option>
                </a-select>
              </div>
            </a-col>
            <a-col :span="24">
              <a-space>
                <div>语速：</div>
                <a-slider v-model:value="speed" :max="2" :min="-2" />
                <a-input-number
                  id="inputNumber"
                  v-model:value="speed"
                  :min="-2"
                  :max="2"
                  size="small"
                  style="width: 60px; margin-left: 30px"
                />
              </a-space>
            </a-col>

            <a-col :span="24">
              <a-space>
                <div>音量：</div>
                <a-slider
                  v-model:value="volume"
                  :max="10"
                  :min="0"
                  style="margin-right: 120px"
                />
                <a-input-number
                  id="inputNumber"
                  v-model:value="volume"
                  :min="0"
                  :max="10"
                  size="small"
                  style="width: 60px; margin-left: 30px"
                />
              </a-space>
            </a-col>
            <a-col :span="24">
              <a-space>
                <div>情感：</div>
                <a-slider
                  v-model:value="emotion_intensity"
                  :max="200"
                  :min="50"
                />
                <a-input-number
                  id="inputNumber"
                  v-model:value="emotion_intensity"
                  :max="200"
                  :min="50"
                  size="small"
                  style="width: 60px; margin-left: 30px"
                />
              </a-space>
            </a-col>
          </a-row>
        </div>
      </a-card>
      <template #footer>
        <div style="text-align: center">
          <a-space>
            <a-button type="default" @click="cancelClick"> 取消 </a-button>
            <a-button type="primary" @click="handleSave"> 保存 </a-button>
          </a-space>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  nextTick,
  watch,
  ref,
  h,
  computed,
  onMounted
} from "vue";
import {
  LoadingOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  CrownOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import request from "@/common/utils/request";
import store from "@/store/index";
function getTextToAudio(params) {
  return request.post("/work_ai", "/user/shotstack/text-to-audio", params);
}
function getVoiceCategory() {
  return request.get("/work_ai", "/user/shotstack/voice/category");
}
function getVoiceCategoryList(params) {
  return request.get("/work_ai", "/user/shotstack/voice/list", params);
}

export default defineComponent({
  name: "DubbingSetting",
  components: {
    PlayCircleOutlined,
    PauseCircleOutlined,
    CrownOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => {},
    },
  },
  setup(props, { emit }) {
    
    const state = reactive({
      appName:  '',
      // 语气
      emotion_category: "",
      toneList: [],
      toneDisabled: true,
      // 语速
      speed: 0,
      // 音频情感程度
      emotion_intensity: 100,
      // 音量
      volume: 5,

      loading: false,
      activeKey: "",
      tabList: [],
      voiceList: [],
      voiceData: {},
      timbreId: 0,

      materialData: {},

      isResultUrl: "",
      playNum: 0,
      content: `欢迎使用${appName.value}视频文字转语音工具`,
      isIndicator: false,
      isPlay: true,
      audioPlayer: null,
      soundLoading: false,
    });

    onMounted(()=>{
      store.dispatch("getAiConfig").then((aiConfig) => {
        state.appName = aiConfig.site_name
      })
    })

    const getList = (key) => {
      state.loading = true;
      getVoiceCategory()
        .then((res) => {
          state.tabList = res.result;
          if (!key) {
            state.activeKey = res.result[0].key;
          }
          state.loading = false;
          getVoiceList(true);
        })
        .catch(() => {
          state.loading = false;
        });
    };

    const getVoiceList = (isFirst) => {
      state.loading = true;
      getVoiceCategoryList({ category: state.activeKey })
        .then((res) => {
          if (res.result.length) {
            state.voiceData = res.result[0].item[0];
            if (!isFirst) {
              state.timbreId = res.result[0].item[0].timbre_id;
            }
            console.log(state.timbreId, state.activeKey);
            state.toneList = res.result[0].item[0].emotion_style;
            res.result.forEach((item) => {
              item.item.forEach((sub) => {
                sub.isPlay = false;
              });
            });
            state.voiceList = res.result;
            state.emotion_category = res.result[0].item[0].emotion_style[0].key;
            if (res.result[0].item[0].emotion_style.length == 1) {
              state.toneDisabled = true;
              state.loading = false;

              return;
            }
            state.toneDisabled = false;
          }
          state.loading = false;
        })
        .catch(() => {
          state.loading = false;
        });
    };

    const voiceClick = (data) => {
      state.voiceData = data;
      state.timbreId = data.timbre_id;
      state.emotion_category = data.emotion_style[0].key;
      state.toneList = data.emotion_style;
      if (data.emotion_style.length == 1) {
        state.toneDisabled = true;
        return;
      }
      state.toneDisabled = false;
    };

    const activeChange = () => {
      getVoiceList();
    };

    // 播放/暂停
    const playbackClick = (data) => {
      data.isPlay = !data.isPlay;
      if (data.isPlay) {
        if (state.audioPlayer) {
          state.audioPlayer.pause(); // 暂停当前播放的音频
          state.audioPlayer.src = "";
        }
        state.audioPlayer = new Audio(data.voice_url); // 播放下一个音频文件
        state.audioPlayer.play(); // 开始播放音频
      } else {
        state.audioPlayer.src = "";
        state.audioPlayer.pause();
      }
      state.voiceList.forEach((voice) => {
        if (voice.item) {
          voice.item.forEach((item) => {
            if (item.id !== data.id) {
              item.isPlay = false;
            }
          });
        }
      });
      if (state.audioPlayer) {
        state.audioPlayer.addEventListener("ended", function () {
          // 这里写入结束回调函数的代码
          console.log("结束语音");
          state.voiceList.forEach((voice) => {
            if (voice.item) {
              voice.item.forEach((item) => {
                if (item.id == data.id) {
                  item.isPlay = false;
                }
              });
            }
          });
        });
      }
    };

    // 播放文案
    const playAutoClick = () => {
      if (state.isResultUrl) {
        state.isPlay = !state.isPlay;
        state.playNum++;
        return;
      }
      if (!state.content) {
        message.warn("请输入文案");
        return;
      }

      let params = {
        content: state.content,
        speed: state.speed,
        voice_type: state.timbreId,
        volume: state.volume,
        emotion_category: state.emotion_category,
        emotion_intensity: state.emotion_intensity,
      };
      state.isIndicator = true;
      getTextToAudio(params).then((res) => {
        if (res?.result?.url) {
          state.isResultUrl = res.result?.url;
          state.isIndicator = false;
          state.isPlay = false;
        }
        // let timer = setInterval(() => {
        //   getTextToAudio.then((task) => {
        //     if (task.result.Data.ResultUrl) {
        //       state.isResultUrl = task.result.Data.ResultUrl;
        //       state.isIndicator = false;
        //       state.isPlay = false;
        //       clearInterval(timer);
        //     }
        //   });
        // }, 1000);
      });
    };

    const audioStatus = (status) => {
      if (status) {
        state.isPlay = true;
      }
    };

    const setAudio = () => {
      state.isPlay = false;
    };

    // 监听输入框变化
    const textareaChange = () => {
      state.isResultUrl = "";
    };

    const handleSave = () => {
      console.log(state.voiceData);
      emit("change", {
        name: state.voiceData.name,
        human_style: state.voiceData.human_style,
        gender_type: state.voiceData?.gender === "female" ? "female" : "male",
        voice_id: state.voiceData.id,
        voice_type: state.timbreId,
        volume: state.volume,
        speed: state.speed,
        // emotion_style_key: state.voiceData?.emotion_style?.[0].key,
        emotion_style_key: state.emotion_category,
        // emotion_category: state.emotion_category,
        emotion_category: state.activeKey,
        emotion_intensity: state.emotion_intensity,
      });
    };

    const indicator = h(LoadingOutlined, {
      style: {
        fontSize: "30px",
      },
      spin: true,
    });

    const cancelClick = () => {
      emit("close");
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          state.voiceData = props.data || {};
          state.content = `欢迎使用${state.appName}视频文字转语音工具`;
          state.speed = props.data?.speed;
          state.emotion_intensity = props.data?.emotion_intensity;
          state.volume = props.data?.volume;
          state.emotion_category = props.data?.emotion_style_key;
          state.activeKey = props.data?.emotion_category;
          state.timbreId = props.data.voice_type;
          getList(state.activeKey);
        } else {
          if (state.audioPlayer) {
            state.audioPlayer.src = "";
            state.audioPlayer?.pause();
          }
          state.isResultUrl = "";
          state.playNum = 0;
          state.content = `欢迎使用${state.appName}视频文字转语音工具`;
          state.isIndicator = false;
          state.isPlay = true;
          state.speed = 0;
          state.emotion_intensity = 150;
          state.volume = 5;
        }
      }
    );

    const title = computed(() => {
      return props.id ? "编辑配音" : "添加配音";
    });

    return {
      ...toRefs(state),
      playbackClick,
      activeChange,
      voiceClick,
      playAutoClick,
      textareaChange,
      cancelClick,
      indicator,
      title,
      audioStatus,
      setAudio,
      handleSave,
    };
  },
});
</script>

<style lang="less" scoped>
.smart-clip {
  padding: 0 20px 20px 20px;
}

button {
  border-radius: 5px;
}

:deep(.ss-select-selector) {
  border-radius: 0 5px 5px 0 !important;
}

.dubbing {
  display: flex;
  width: 100%;
}
.copywriting {
  display: flex;
  margin-bottom: 20px;
}
.dubbing-title,
.copywriting-title {
  display: flex;
  width: 60px;
  padding: 12px 0;
}

.ss-card {
  border-radius: 10px;
  margin: 5px 0;
}

.voice-content {
  margin-top: 20px;
  width: 100%;
  height: 400px;
  overflow: auto;
}
.n-tab-pane {
  display: flex;

  .group-box {
    display: flex;
    align-items: center;
    width: 185px;
    height: 75px;
    padding: 30px 15px;
    margin-bottom: 20px;
    margin-right: 20px;
    border-radius: 5px;
    border: 1px solid #d9d9d9;
    cursor: pointer;
    position: relative;

    &.group-border {
      border: 1px solid #436ba0;
    }
    .avatar {
      margin-right: 5px;
    }
    .mask {
      position: absolute;
      top: 21px;
      left: 15px;
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
      .icon {
        margin-top: 7px;
        margin-left: 7px;
        color: #fff;
        font-size: 18px;
      }
      display: none;
    }
    :hover {
      .mask {
        display: block;
      }
    }
    .right-badge {
      position: absolute;
      top: 0;
      right: 0;
      width: auto;
      height: 20px;
      padding: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 12px;
      border-radius: 2px;
      background: #ff9c00;
    }
  }
}

.group-title {
  width: 90px;
  // display: flex;
  // justify-content: center;
}

.role_box {
  width: calc(100% - 100px);
  display: flex;
  flex-wrap: wrap;
}

.role_item {
  flex: 0 0 25%;
  height: 40px;
}

:deep(.ss-radio-wrapper) {
  margin-right: 0px;
}

.ss-radio-group {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.group-name {
  width: 80px;
}
.voice {
  margin-top: 15px;
  margin-bottom: 30px;
}
.voice-item {
  width: 100%;
  display: flex;
  align-items: center;
}
.ss-slider {
  width: 500px;
}
.textarea-wrapper {
  width: 100%;
  position: relative;
  border: 1px solid #eaeaea;
  padding: 20px;
  position: relative;
  .mask-text {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.5);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .mask-box {
      width: 176px;
      height: 62px;
      background: #d1d5db;
      color: #2878FF;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 15px;
    }
  }
}
.operation {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 20px;
  .auto-box {
    margin-right: 10px;
  }
}
.operation-btn {
  font-size: 24px;
  color: #666;
  margin-left: 10px;
  cursor: pointer;
}
.add-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  margin-left: 95px;
}
:deep(.ss-card-body) {
  padding-top: 0;
}

.footer {
  width: 100%;
  text-align: center;
}
:deep(.ss-slider) {
  width: 500px;
}
</style>
